import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author wangj881
 * @date 2024-11-28 16:12
 */
public class L216_2 {
    public static void main(String[] args) {
        int k = 3;
        int n = 7;
        List<List<Integer>> lists = new Solution().combinationSum3(k, n);
        for (List<Integer> list : lists) {
            System.out.println(list.toString());
        }

    }

    static class Solution {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> node = new LinkedList<>();

        public List<List<Integer>> combinationSum3(int k, int n) {
            backTracking(k, n, 1);
            return result;
        }

        private void backTracking(int k, int n, int start) {
            if (node.size() == k) {
                if (n == 0) {
                    result.add(new ArrayList<>(node));
                }
                return;
            }
            for (int i = start; i <= 9; i++) {
                n -= i;
                node.add(i);
                backTracking(k, n, i + 1);
                node.removeLast();
                n += i;
            }
        }
    }
}
